<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="问题标题" prop="questionTitle">
        <el-input v-model="formData.questionTitle" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="适用品类" prop="categoryId">
        <el-tree-select
          v-model="formData.categoryId"
          :data="categoryTree"
          :props="{ ...defaultProps, label: 'categoryName' }"
          check-strictly
          default-expand-all
          placeholder="请选择"
        />
      </el-form-item>
      <el-form-item label="问题类型" prop="questionType">
        <el-select v-model="formData.questionType" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.QUESTION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="选项列表"
        prop="options"
        v-if="formData.questionType && formData.questionType !== 3"
      >
        <div class="options-container">
          <div v-for="(option, index) in formData.options" :key="index" class="option-item">
            <el-input v-model="option.queSort" placeholder="排序" style="width: 20%" />
            <el-input v-model="option.queContent" placeholder="选项内容" style="width: 20%" />
            <el-input v-model="option.remarks" placeholder="备注" style="width: 20%" />
            <UploadImg v-model="option.imgRul" style="width: 20%" />
            <el-button circle type="danger" @click="removeOption(index)" icon="Delete" />
          </div>
          <el-button @click="addOption">添加选项</el-button>
        </div>
      </el-form-item>

      <!-- 文本类型输入框 -->
      <el-form-item label="答案格式" prop="textConfig" v-if="formData.questionType === 3">
        <el-input v-model="formData.textConfig.placeholder" placeholder="输入框提示文本" />
        <div class="mt-2">
          <el-radio-group v-model="formData.textConfig.inputType">
            <el-radio :label="0">文本</el-radio>
            <el-radio :label="1">数字</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.GlOBAL_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="图片" prop="imgRul">
        <UploadImg v-model="formData.imgRul" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { QuestionApi, Question } from '@/api/recycling/question'
import { CategoryApi, Category } from '@/api/recycling/category'
import { defaultProps, handleTree } from '@/utils/tree'

/** 回收问题选项 表单 */
defineOptions({ name: 'QuestionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const categoryTree = ref() // 树形结构

// 类型定义
interface OptionItem {
  queSort: string
  queContent: string
  remarks: string
  imgRul: string
}

interface TextConfig {
  placeholder: string
  inputType: number // 0-文本 1-数字
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  questionTitle: undefined,
  categoryId: undefined,
  questionType: undefined,
  status: undefined,
  sort: undefined,
  imgRul: undefined,
  options: [] as OptionItem[],
  textConfig: {
    placeholder: '',
    inputType: 0
  } as TextConfig
})
// 添加选项
const addOption = () => {
  formData.value.options.push({
    queSort: String(formData.value.options.length + 1),
    queContent: '',
    remarks: '',
    imgRul: ''
  })
}
// 删除选项
const removeOption = (index: number) => {
  formData.value.options.splice(index, 1)
}

const formRef = ref() // 表单 Ref
// 修改 open 方法中的数据获取部分
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await QuestionApi.getQuestion(id)

      // 直接赋值基础字段
      formData.value = {
        ...res,
        // 特殊处理 options 字段
        options: res.options ? parseOptions(res.options, res.questionType) : []
      }

      // 单独处理文本配置
      if (res.questionType === 3 && res.options) {
        try {
          const parsed = JSON.parse(res.options)
          if (parsed.config) {
            formData.value.textConfig = parsed.config
          }
        } catch (e) {
          console.error('解析文本配置失败', e)
        }
      }
    } finally {
      formLoading.value = false
    }
  }
  await getCategoryTree()
}

// 新增：解析选项的通用方法
// 解析选项的通用方法
const parseOptions = (optionsString: string, questionType: number): OptionItem[] => {
  try {
    // 去除多余的双引号
    const cleanStr = optionsString.replace(/^"|"$/g, '')
    const parsed = JSON.parse(cleanStr)

    if (questionType !== 3 && Array.isArray(parsed)) {
      return parsed.map((item: any) => ({
        queSort: item.queSort || String(item.sort || ''),
        queContent: item.queContent || item.content || '',
        remarks: item.remarks || '',
        imgRul: item.imgRul || item.imgUrl || ''
      }))
    }

    return []
  } catch (error) {
    console.warn('解析选项失败，使用兼容模式', error)
    return []
  }
}
// 修改 beforeSubmit 方法
const beforeSubmit = () => {
  // 构建最终提交数据
  const submitData = { ...formData.value }

  // 根据问题类型处理选项数据
  if (submitData.questionType === 3) {
    // 文本类型
    submitData.options = JSON.stringify({
      type: 'text',
      config: submitData.textConfig
    })
  } else {
    // 单选/多选类型
    submitData.options = JSON.stringify(
      submitData.options.map((opt) => ({
        queSort: opt.queSort,
        queContent: opt.queContent,
        remarks: opt.remarks,
        imgRul: opt.imgRul
      }))
    )
  }

  // 清除不需要提交的字段
  delete submitData.textConfig
  return submitData
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 提交前处理数据
    const submitData = beforeSubmit()

    if (formType.value === 'create') {
      await QuestionApi.createQuestion(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await QuestionApi.updateQuestion(submitData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 获得回收品类树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryList()
  const root: Tree = { id: 0, name: '顶级回收品类', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  categoryTree.value.push(root)
}

// 编辑时数据回填
// const fetchData = async (id: number) => {
//   const data = await QuestionApi.getQuestion(id)

//   if (data.options) {
//     try {
//       const parsed = JSON.parse(data.options)

//       if (parsed.type === 'text') {
//         formData.value.textConfig = parsed.config
//       } else {
//         formData.value.options = parsed.map((item: any) => ({
//           title: item.label,
//           value: item.value
//         }))
//       }
//     } catch {
//       // 兼容旧数据格式
//       formData.value.options = data.options.split(',').map((opt: string) => ({
//         title: opt,
//         value: opt
//       }))
//     }
//   }
// }

// 表单验证规则
const formRules = {
  imgRul: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  options: {
    validator: (rule: any, value: OptionItem[], callback: Function) => {
      if (formData.value.questionType === 3) return callback()

      if (value.length === 0) {
        callback(new Error('至少需要添加一个选项'))
      } else if (value.some((opt) => !opt.queContent)) {
        callback(new Error('请填写选项内容'))
      } else {
        callback()
      }
    }
  },
  textConfig: {
    validator: (rule: any, value: TextConfig, callback: Function) => {
      if (formData.value.questionType !== 3) return callback()

      if (!value.placeholder) {
        callback(new Error('请输入提示文本'))
      } else {
        callback()
      }
    }
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    questionTitle: undefined,
    categoryId: undefined,
    questionType: undefined,
    options: [],
    textConfig: {
      placeholder: '',
      inputType: 0
    },
    status: undefined,
    sort: undefined,
    imgRul: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}
</style>
